package campshop.daos;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import campshop.models.ShopInfo;
public class ShopInfoDao extends JdbcDaoSupport{
	public long addShopInfo(ShopInfo si)
	{
		String sql = "insert into " +
				"tbl_shop_info (cs_uId, si_sShopName, si_sProvince, sr_uSchoolId, sbr_uId, si_uRoomNum, si_dCreateDate, si_sDesInfo, si_sImagePath)" +
				" values (?, ?, ?, ?, ?, ?, ?, ?, ?)";
		if(super.getJdbcTemplate().update(sql, si.getuOwnerId(), si.getsShopName(), si.getsProvince(), si.getuSchoolId(), si.getuSchoolBuildingId()
				, si.getuRoomId(), si.getdCreateDate(), si.getsDesInfo(), si.getsImagePath())>0){
			return super.getJdbcTemplate().queryForInt("select max(si_uShopId) from tbl_shop_info");
		}else return 0L;
	}
	
	public boolean delShopInfo(long uId)
	{
		String sql = "delete from tbl_shop_info where si_uShopId = ?";
		if(super.getJdbcTemplate().update(sql, uId)>0) return true;
		return false;
	}
	
	public boolean updateShopInfo(ShopInfo si) {
		String sql="update tbl_shop_info " +
				"set cs_uId=?, si_sShopName=?, si_sProvince=?, sr_uSchoolId=?, sbr_uId=?, si_uRoomNum=?, si_dCreateDate=?, si_sDesInfo=?, si_sImagePath=? " +
				"where si_uShopId = ?";
		if(super.getJdbcTemplate().update(sql, si.getuOwnerId(), si.getsShopName(), si.getsProvince(), si.getuSchoolId(), si.getuSchoolBuildingId()
				, si.getuRoomId(), si.getdCreateDate(), si.getsDesInfo(), si.getsImagePath(), si.getuShopId())>0){
			return true;
		}else return false;
	}
	
	public ShopInfo getShopInfo(long uId)
	{
		String sql = "select * from tbl_shop_info where si_uShopId=" + uId;
		return (ShopInfo)super.getJdbcTemplate().queryForObject(sql, new ShopInfoRowMapper());
	}
	
	class ShopInfoRowMapper implements RowMapper<ShopInfo>{
		@Override
		public ShopInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
			ShopInfo si = new ShopInfo();
			si.setuShopId(rs.getLong("si_uShopId"));
			si.setuOwnerId(rs.getLong("cs_uId"));
			si.setsShopName(rs.getString("si_sShopName"));
			si.setsProvince(rs.getString("si_sProvince"));
			si.setuSchoolId(rs.getLong("sr_uSchoolId"));
			si.setuSchoolBuildingId(rs.getLong("sbr_uId"));
			si.setuRoomId(rs.getLong("si_uRoomNum"));
			si.setdCreateDate(rs.getDate("si_dCreateDate"));
			si.setsDesInfo(rs.getString("si_sDesInfo"));
			si.setsImagePath(rs.getString("si_sImagePath"));
			return si;
		}	
	}
}